package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.json.JsonOutput
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_HEAD_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_PRODUCT_MANAGER', 'ROLE_SECOND_BRANCH_OFFICE_PRODUCT_MANAGER',
    'ROLE_SECOND_BRANCH_OFFICE_DIRECTOR', 'ROLE_ACCOUNT_MANAGER', 'ROLE_SALES_REPRESENTATIVE', 'ROLE_BANK_OUTLETS_ADMINISTRATOR', 'ROLE_MERCHANT_ADMINISTRATOR', 'ROLE_CHANNEL_ADMINISTRATOR'])
@Transactional(readOnly = true)
class BocUserController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def type = UserType.findByName("机构柜员")
        def userList = User.findAll("from User where type.id = ${type.id}", [max: params.max, offset: params.offset])
        def userCount = User.executeQuery("select count(id) from User where type.id = ${type.id}")[0]
        respond userList, model: [userCount: userCount]
    }

    def index1(Integer max)
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def type = UserType.findByName("商户柜员")
        def userList = User.findAll("from User where type.id = ${type.id}", [max: params.max, offset: params.offset])
        def userCount = User.executeQuery("select count(id) from User where type.id = ${type.id}")[0]
        respond userList, model: [userCount: userCount]
    }

    def channelIndex(Integer max)
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def type = UserType.findByName("渠道柜员")
        def userList = User.findAll("from User where type.id = ${type.id}", [max: params.max, offset: params.offset])
        def userCount = User.executeQuery("select count(id) from User where type.id = ${type.id}")[0]
        respond userList, model: [userCount: userCount]
    }

    @Transactional
    def searchUser()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def account = params["account"]
        def username = params["username"]
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]

        def type = UserType.findByName("机构柜员")

        String sql = "from User as u where u.type = ${type.id}"

        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (account)
        {
            sql += " and u.account.name = '${account}'"
        }
        if (username)
        {
            sql += " and u.username = '${username}'"
        }
        if (cellphone)
        {
            sql += " and u.cellphone = '${cellphone}'"
        }

        def max = params.max
        def offset = params.offset

        def list = User.findAll(sql, [max: max, offset: offset])
        def list1 = User.findAll(sql)
        def count = list1.size()

        respond list, model: [userCount: count, params: params], view: 'index'
    }

    @Transactional
    def searchUser1()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def account = params["account"]
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]

        def type = UserType.findByName("商户柜员")

        String sql = "from User as u where u.type = ${type.id}"

        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (account)
        {
            sql += " and u.account.name = '${account}'"
        }
        if (cellphone)
        {
            sql += " and u.cellphone = '${cellphone}'"
        }

        def max = params.max
        def offset = params.offset

        def list = User.findAll(sql, [max: max, offset: offset])
        def list1 = User.findAll(sql)
        def count = list1.size()

        respond list, model: [userCount: count, params: params], view: 'index'
    }

    @Transactional
    def channelSearchUser()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def account = params["account"]
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]

        def type = UserType.findByName("渠道柜员")

        String sql = "from User as u where u.type = ${type.id}"

        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (account)
        {
            sql += " and u.account.name = '${account}'"
        }
        if (cellphone)
        {
            sql += " and u.cellphone = '${cellphone}'"
        }

        def max = params.max
        def offset = params.offset

        def list = User.findAll(sql, [max: max, offset: offset])
        def list1 = User.findAll(sql)
        def count = list1.size()

        respond list, model: [userCount: count, params: params], view: 'channelIndex'
    }

    def show(User user)
    {
        def userRoleList = UserRole.findAllByUser(user)
        respond user, model: [userRoleList: userRoleList]
    }

    def create()
    {
        def accounts = Account.findAllByType(AccountType.findByName("机构"))
        def userLevels = UserLevel.findAll()
        def userType = UserType.findByName("机构柜员")
        respond new User(params), model: [accounts: accounts, userLevels: userLevels, userType: userType]
    }

    def create1()
    {
        def accounts = Account.findAllByType(AccountType.findByName("商户"))
        def userType = UserType.findByName("商户柜员")
        respond new User(params), model: [accounts: accounts, userType: userType]
    }

    def channelCreate()
    {
        def accounts = Account.findAllByType(AccountType.findByName("渠道"))
        def userType = UserType.findByName("渠道柜员")
        respond new User(params), model: [accounts: accounts, userType: userType]
    }

    @Transactional
    def save(User user)
    {
        def accounts = Account.findAllByType(AccountType.findByName("机构"))
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'create', model: [accounts: accounts]
            return
        }

        // user.code = userService.generateCode()

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: 'show', id: user?.id
            }
            '*' { respond user, [status: CREATED] }
        }
    }

    @Transactional
    def save1(User user)
    {
        def accounts = Account.findAllByType(AccountType.findByName("商户"))
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'create1', model: [accounts: accounts]
            return
        }

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: 'show1', id: user?.id
            }
            '*' { respond user, [status: CREATED] }
        }
    }

    @Transactional
    def channelSave(User user)
    {
        def accounts = Account.findAllByType(AccountType.findByName("渠道"))
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'channelCreate', model: [accounts: accounts]
            return
        }

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: 'channelShow', id: user?.id
            }
            '*' { respond user, [status: CREATED] }
        }
    }

    def show1(User user)
    {
        respond user
    }

    def channelShow(User user)
    {
        respond user
    }

    def edit(User user)
    {
        def accounts = Account.findAllByType(AccountType.findByName("机构"))
        respond user, model: [accounts: accounts]
    }

    def edit1(User user)
    {
        def accounts = Account.findAllByType(AccountType.findByName("商户"))
        respond user, model: [accounts: accounts]
    }

    def channelEdit(User user)
    {
        def accounts = Account.findAllByType(AccountType.findByName("渠道"))
        respond user, model: [accounts: accounts]
    }

    @Transactional
    def update(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'edit'
            return
        }

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: 'show', id: user?.id
            }
            '*' { respond user, [status: OK] }
        }
    }

    @Transactional
    def update1(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'edit1'
            return
        }

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: 'show1', id: user?.id
            }
            '*' { respond user, [status: OK] }
        }
    }

    @Transactional
    def channelUpdate(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'channelEdit'
            return
        }

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: 'channelShow', id: user?.id
            }
            '*' { respond user, [status: OK] }
        }
    }

    @Transactional
    def delete(User user)
    {

        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        user.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label',
                                                                                          default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def deleteRole()
    {
        String userId = params["userId"]
        String roleId = params["roleId"]
        def userRole = UserRole.findByUserAndRole(User.findById(userId), Role.findById(roleId))

        if (userRole == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        userRole.delete flush: true

        redirect uri: request.getHeader("referer")
    }
}
